package com.remoter.transport.netty.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.remoter.api.configure.IConfiguration;
import com.remoter.api.configure.support.AbstractConfiguration;
import com.remoter.api.extension.support.ExtensionLoader;
import com.remoter.api.protocol.support.RemoterRequest;
import com.remoter.api.protocol.support.RemoterResponse;
import com.remoter.api.transport.IMessageTask;
import com.remoter.api.transport.IMessageTaskFilter;
import com.remoter.api.util.Final;
import com.remoter.api.util.ObjectChain;
import com.remoter.api.util.StringUtil;
import com.remoter.transport.netty.util.FinalTransportNetty;

public class NettyServerMessageTask implements IMessageTask{
	
	private static final Logger log = LoggerFactory.getLogger(NettyServerMessageTask.class);
	private final RemoterRequest remoterRequest;
	private final RemoterResponse remoterResponse;
	private final IConfiguration configuration;
	private final ObjectChain<IMessageTaskFilter> chain;
	
	public NettyServerMessageTask(RemoterRequest remoterRequest,RemoterResponse remoterResponse){
		this.remoterRequest = remoterRequest;
		this.remoterResponse = remoterResponse;
		this.configuration = AbstractConfiguration.getConfiguration();
		this.chain = new ObjectChain<IMessageTaskFilter>();
		this.initFilter(this.configuration.getOption(FinalTransportNetty.O_TRANSPORT_SERVER_FILTER));
	}
	
	@Override
	public Boolean call() throws Exception {
		if(null != this.chain){
			this.chain.rewind();
			if(this.chain.hasNext()){
				this.chain.next().execute(this.remoterRequest,this.remoterResponse,this.chain);
			}
		}
		return true;
	}
	
	private void initFilter(String filterString){
		if(StringUtil.isBlank(filterString)){
			return;
		}
		String[] filters = filterString.split(Final.D_DATA_SEPARATOR);
		if(null == filters || filters.length == 0){
			return;
		}
		for(String filter : filters){
			if(StringUtil.isBlank(filter)){
				log.warn("IMessageTaskFilter name is empty !");
			}else{
				IMessageTaskFilter f = ExtensionLoader.getService(IMessageTaskFilter.class,filter);
				if(null == f){
					log.warn("IMessageTaskFilter not found : "+filter);
				}else{
					this.chain.add(f);
					log.debug("IMessageTaskFilter add success : " + filter);
				}
			}
		}
	}
	
}